const jwt = require('jsonwebtoken');
const User = require('../models/User');

// 生成 JWT 的函数
exports.generateJWT = (userId, role) => {
  return jwt.sign({ id: userId, role: role }, process.env.JWT_SECRET, { expiresIn: '1d' });
};

// 角色检查中间件
exports.requireRole = (...roles) => {
  return (req, res, next) => {
    if (!roles.includes(req.user.role)) {
      return res.status(403).json({
        status: 'fail',
        message: '无权执行此操作'
      });
    }
    next();
  };
};

// 主认证中间件
exports.protect = async (req, res, next) => {
  try {
    // 公开路由列表
    const publicRoutes = ['/login', '/register', '/home'];

    // 如果是公开路由，直接放行
    if (publicRoutes.includes(req.path)) {
      return next();
    }

    // 1. 获取token
    let token;
    if (
      req.headers.authorization &&
      req.headers.authorization.startsWith('Bearer')
    ) {
      token = req.headers.authorization.split(' ')[1];
    }

    if (!token) {
      return res.status(401).json({
        status: 'fail',
        message: '请登录后访问'
      });
    }

    // 2. 验证token
    const decoded = jwt.verify(token, process.env.JWT_SECRET);

    // 3. 检查用户是否存在
    const currentUser = await User.findById(decoded.id);
    if (!currentUser) {
      return res.status(401).json({
        status: 'fail',
        message: '用户不存在'
      });
    }

    // 4. 挂载用户到请求对象
    req.user = {
      id: currentUser._id,
      role: currentUser.role,
      username: currentUser.username, // 确保用户名被正确设置
      permissions: decoded.permissions
    };

    next();
  } catch (err) {
    console.error('JWT 验证失败:', err); // 添加详细的错误日志
    res.status(401).json({
      status: 'fail',
      message: '认证失败'
    });
  }
};
